package net.dnw.practicesummary.mvp.net;



import net.dnw.practicesummary.mvp.utils.Logger;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import javax.net.ssl.SSLHandshakeException;

import io.reactivex.observers.DisposableObserver;
import retrofit2.HttpException;


/**
 * 处理请求响应数据
 */

public abstract class BaseDisposableObserver<T> extends DisposableObserver<T> {

    @Override
    public void onNext(T responseBody) {
        responseResult(responseBody);
        destory();

    }


    @Override
    public void onError(Throwable e) {
        try {

            if (e instanceof SocketTimeoutException) {//请求超时

            } else if (e instanceof ConnectException) {//网络连接超时
                errorResult(e,"网络连接超时");
            } else if (e instanceof SSLHandshakeException) {//安全证书异常
                errorResult(e,"安全证书异常");
            } else if (e instanceof HttpException) {//请求的地址不存在
                int code = ((HttpException) e).code();
                if (code == 504) {
                    errorResult(e,"网络异常，请检查您的网络状态");
                } else if (code == 404) {
                    errorResult(e,"请求的地址不存在");
                } else {
                    errorResult(e,"请求失败");
                }
            } else if (e instanceof UnknownHostException) {//域名解析失败
                errorResult(e,"域名解析失败");
            } else {
                if (e != null) {
                    errorResult(e, "域名解析失败" + e.getMessage());
                } else {
                    errorResult(e, "" + e);
                }
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        } finally {
            Logger.e("OnSuccessAndFaultSub", "error:" + e.getMessage());
        }
        destory();
    }

    @Override
    public void onComplete() {
        destory();
    }


    private void destory() {
        if (!this.isDisposed()) {
            this.dispose();
        }
    }

    public abstract void responseResult(T result);

    public abstract void errorResult(Throwable e,String errorMsg);
}
